package com.mzba.easy.weibo.db;

import android.content.ContentValues;
import android.database.Cursor;

/**
 * @author 06peng
 *
 */
public class AccessTokenTable {

	public static final String TABLE_NAME = "access_token_tb";
	public static final String ID = "_id";
	public static final String REMIND_IN = "remind_in";
	public static final String ACCESS_TOKEN = "access_Token";
	public static final String EXPIRES_IN = "expires_in";
	public static final String UID = "uid";
	public static final String OAUTH_TIME = "oauth_time";
	
	private DBManagerImpl db = null;
	
	public AccessTokenTable() {
		if (db == null) {
			db = DBManager.get();
		}
		if (!db.isTableExits(db.getConnection(), TABLE_NAME)) {
			createTable();
		}
	}
	
	private void createTable() {
		String createSql = "create table if not exists " + TABLE_NAME + " ("
				+ ID + " int primary key," + REMIND_IN + " varchar, "+ACCESS_TOKEN+" varchar, "
				+ EXPIRES_IN + " varchar," + UID + " varchar, " + OAUTH_TIME + " varchar)";
		db.creatTable(db.getConnection(), createSql, TABLE_NAME);
	}
	
	public void save(AccessTokenEntry entry) {
		db.delete(db.getConnection(), TABLE_NAME, null, null);
		ContentValues values = new ContentValues();
		values.put(REMIND_IN, entry.getRemind_in());
		values.put(UID, entry.getUid());
		values.put(ACCESS_TOKEN, entry.getAccess_token());
		values.put(EXPIRES_IN, entry.getExpires_in());
		values.put(OAUTH_TIME, String.valueOf(entry.getOauthTime()));
		db.save(db.getConnection(), TABLE_NAME, values);
	}
	
	public AccessTokenEntry getAccessToken() {
		Cursor cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME, null);
		if (cursor == null)
			return null;
		AccessTokenEntry entry = null;
		try {
			while (cursor.moveToNext()) {
				entry = new AccessTokenEntry();
				entry.setAccess_token(cursor.getString(cursor.getColumnIndex(ACCESS_TOKEN)));
				entry.setUid(cursor.getString(cursor.getColumnIndex(UID)));
				entry.setExpires_in(cursor.getString(cursor.getColumnIndex(EXPIRES_IN)));
				entry.setRemind_in(cursor.getString(cursor.getColumnIndex(REMIND_IN)));
				entry.setOauthTime(Long.parseLong(cursor.getString(cursor.getColumnIndex(OAUTH_TIME))));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
		return entry;
	}
}
